"""
浏览器Cookie自动获取工具
用于自动打开浏览器并获取闲鱼Cookie
"""

import os
import sys
import time
from typing import Optional
from loguru import logger

try:
    from selenium import webdriver
    from selenium.webdriver.chrome.service import Service
    from selenium.webdriver.chrome.options import Options
    from webdriver_manager.chrome import ChromeDriverManager
    SELENIUM_AVAILABLE = True
except ImportError:
    SELENIUM_AVAILABLE = False


def find_chrome_path() -> Optional[str]:
    """
    自动识别系统中Chrome浏览器的安装路径
    
    返回:
        Optional[str]: Chrome浏览器可执行文件的完整路径，如果未找到则返回None
    """
    # Windows系统常见的Chrome安装路径
    possible_paths = [
        r"C:\Program Files\Google\Chrome\Application\chrome.exe",
        r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
        os.path.expanduser(r"~\AppData\Local\Google\Chrome\Application\chrome.exe"),
    ]
    
    for path in possible_paths:
        if os.path.exists(path):
            logger.info(f"找到Chrome浏览器: {path}")
            return path
    
    logger.warning("未找到Chrome浏览器，将使用系统默认路径")
    return None


class BrowserCookieFetcher:
    """
    浏览器Cookie获取器
    使用Selenium自动化工具启动浏览器并获取Cookie
    """
    
    def __init__(self):
        """初始化浏览器Cookie获取器"""
        self.driver: Optional[webdriver.Chrome] = None
        self.target_url = "https://www.goofish.com/im"
        
        if not SELENIUM_AVAILABLE:
            raise ImportError("selenium库未安装，请先运行: pip install selenium webdriver-manager")
    
    def open_browser_for_login(self) -> bool:
        """
        启动浏览器并打开闲鱼登录页面
        
        返回:
            bool: 成功返回True，失败返回False
        """
        try:
            # 配置Chrome选项
            chrome_options = Options()
            chrome_options.add_argument('--start-maximized')  # 最大化窗口
            chrome_options.add_argument('--disable-blink-features=AutomationControlled')  # 隐藏自动化特征
            chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])  # 禁用自动化提示
            chrome_options.add_experimental_option('useAutomationExtension', False)  # 禁用自动化扩展
            
            # 查找Chrome浏览器路径
            chrome_path = find_chrome_path()
            if chrome_path:
                chrome_options.binary_location = chrome_path
            
            # 启动Chrome浏览器
            logger.info("正在启动Chrome浏览器...")
            
            candidates = []
            try:
                meipass = getattr(sys, "_MEIPASS", None)
            except Exception:
                meipass = None
            if meipass:
                candidates.append(os.path.join(meipass, "utils", "chromedriver.exe"))
            candidates.append(os.path.join(os.path.dirname(__file__), "chromedriver.exe"))
            candidates.append(os.path.join(os.getcwd(), "utils", "chromedriver.exe"))
            driver_path = None
            for p in candidates:
                if os.path.exists(p):
                    driver_path = p
                    break
            if driver_path:
                logger.info(f"使用本地chromedriver: {driver_path}")
            else:
                try:
                    logger.warning("未发现本地chromedriver，尝试自动下载...")
                    driver_path = ChromeDriverManager().install()
                    logger.info(f"使用自动下载chromedriver: {driver_path}")
                except Exception as e:
                    logger.error(f"chromedriver不可用且下载失败: {e}")
                    return False
            
            # 创建Service对象
            from selenium.webdriver.chrome.service import Service as ChromeService
            service = ChromeService(executable_path=driver_path)
            
            # 启动Chrome浏览器
            self.driver = webdriver.Chrome(service=service, options=chrome_options)
            logger.info("Chrome浏览器启动成功")
            
            # 设置隐式等待时间
            self.driver.implicitly_wait(10)
            
            # 打开淘宝登录页面（闲鱼使用淘宝账号登录）
            logger.info(f"正在打开页面: {self.target_url}")
            self.driver.get(self.target_url)
            
            # 等待页面加载
            time.sleep(2)
            
            logger.info("浏览器已打开，请手动登录账号")
            return True
            
        except Exception as e:
            logger.error(f"启动浏览器过程发生未捕获异常: {str(e)}")
            if self.driver:
                self.driver.quit()
                self.driver = None
            return False
    
    def get_cookies(self) -> Optional[str]:
        """
        从浏览器获取Cookie字符串
        
        返回:
            Optional[str]: Cookie字符串，格式为"key1=value1; key2=value2; ..."，失败返回None
        """
        try:
            if not self.driver:
                logger.error("浏览器未启动，无法获取Cookie")
                return None
            
            logger.info("正在读取 h5api.m.goofish.com 域Cookie...")
            target_host = "h5api.m.goofish.com"
            cookies = []
            try:
                res = self.driver.execute_cdp_cmd("Network.getCookies", {"urls": ["https://h5api.m.goofish.com/h5/mtop.taobao.idlemessage.pc.user.query/4.0/"]})
                cdp_list = res.get("cookies", [])
                for c in cdp_list:
                    d = (c.get("domain", "") or "").lstrip('.')
                    if d and (d == target_host or target_host.endswith('.' + d)):
                        cookies.append({"name": c.get("name", ""), "value": c.get("value", "")})
            except Exception as e:
                logger.debug(f"CDP获取Cookies失败: {str(e)}")
                base_list = self.driver.get_cookies()
                for c in base_list:
                    d = (c.get("domain", "") or "").lstrip('.')
                    if d and (target_host == d or target_host.endswith('.' + d)):
                        cookies.append({"name": c.get("name", ""), "value": c.get("value", "")})
            
            if not cookies:
                logger.warning("未获取到任何Cookie")
                return None
            
            # 将Cookie列表转换为字符串格式
            cookie_str = "; ".join([f"{cookie['name']}={cookie['value']}" for cookie in cookies])
            
            logger.info(f"成功获取Cookie，长度: {len(cookie_str)}")
            return cookie_str
            
        except Exception as e:
            logger.error(f"获取Cookie失败: {str(e)}")
            return None
    
    def close_browser(self):
        """
        关闭浏览器并清理资源
        """
        try:
            if self.driver:
                logger.info("正在关闭浏览器...")
                self.driver.quit()
                self.driver = None
                logger.info("浏览器已关闭")
        except Exception as e:
            logger.error(f"关闭浏览器失败: {str(e)}")

    def __del__(self):
        try:
            self.close_browser()
        except Exception:
            pass
    
    def is_browser_open(self) -> bool:
        """
        检查浏览器是否处于打开状态
        
        返回:
            bool: 浏览器打开返回True，否则返回False
        """
        try:
            if self.driver:
                # 尝试获取当前URL，如果浏览器已关闭会抛出异常
                _ = self.driver.current_url
                return True
        except Exception:
            self.driver = None
        return False


# 模块测试代码
if __name__ == "__main__":
    """测试浏览器Cookie获取功能"""
    print("=== 浏览器Cookie获取工具测试 ===")
    
    # 创建Cookie获取器
    fetcher = BrowserCookieFetcher()
    
    # 打开浏览器
    if fetcher.open_browser_for_login():
        print("浏览器已打开，请在浏览器中完成登录...")
        print("等待8秒后自动获取Cookie...")
        time.sleep(8)
        
        # 获取Cookie
        cookie_str = fetcher.get_cookies()
        if cookie_str:
            print(f"\n获取到的Cookie:\n{cookie_str[:100]}...")
            print(f"Cookie总长度: {len(cookie_str)}")
        else:
            print("未能获取到Cookie")
        
        # 关闭浏览器
        fetcher.close_browser()
    else:
        print("浏览器启动失败")
